package club.zhcs.capture.biz.auth.impl;

import static club.zhcs.capture.vo.Consts.SystemValues.*;
import static org.nutz.lang.Times.now;

import java.util.Collections;
import java.util.List;

import club.zhcs.capture.bean.auth.Role;
import club.zhcs.capture.bean.auth.RolePermission;
import club.zhcs.capture.biz.auth.IRoleService;
import club.zhcs.capture.dao.IRoleDao;
import club.zhcs.capture.dao.impl.RolePermissionDao;

import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.ContinueLoop;
import org.nutz.lang.Each;
import org.nutz.lang.ExitLoop;
import org.nutz.lang.Lang;
import org.nutz.lang.LoopException;

import com.dgj.utils.collection.Lists;
import com.dgj.utils.db.SqlActuator;
import com.dgj.utils.entries.Result;
import com.dgj.utils.web.pager.Pager;

@IocBean(name = "roleService")
public class RoleService implements IRoleService {

	@Inject
	IRoleDao roleDao;

	@Inject
	PropertiesProxy sqls;

	@Inject
	private RolePermissionDao rolePermissionDao;

	@Override
	public List<Role> findByUserId(int id) {
		final Dao dao = roleDao.getDao();// 获取数据访问对象

		final List<Role> roles = Lists.newArrayList();
		// 获取配置的sql
		Sql sql = Sqls.create("SELECT * FROM gj_role WHERE id in (SELECT DISTINCT r_id FROM gj_user_role WHERE u_id = @userid)");

		sql.params().set("userid", id);// 注入sql参数

		List<Record> records = SqlActuator.runReport(sql, dao);// 执行sql

		Lang.each(records, new Each<Record>()// 将记录转换成对象
				{

					@Override
					public void invoke(int index, Record record, int length) throws ExitLoop, ContinueLoop, LoopException {
						roles.add(record.toEntity(dao.getEntity(Role.class)));
					}
				});

		return roles;
	}

	@Override
	public List<Role> findByPositions(int[] positions) {

		if (positions == null || positions.length == 0)// 空对空
		{
			return Lists.newArrayList();
		}

		final Dao dao = roleDao.getDao();// 获取数据访问对象

		final List<Role> roles = Lists.newArrayList();
		// 获取配置的sql
		Sql sql = Sqls.create(sqls.get("find.roles.by.positions"));

		sql.setCondition(Cnd.where("position_id", "IN", positions));

		List<Record> records = SqlActuator.runReport(sql, dao);// 执行sql

		Lang.each(records, new Each<Record>()// 将记录转换成对象
				{

					@Override
					public void invoke(int index, Record record, int length) throws ExitLoop, ContinueLoop, LoopException {
						roles.add(record.toEntity(dao.getEntity(Role.class)));
					}
				});

		return roles;
	}

	@Override
	public List<Role> findByPositionIds(List<Integer> positions) {

		if (positions == null || positions.size() == 0)// 空对空
		{
			return Lists.newArrayList();
		}

		final int[] temp = new int[positions.size()];// list转换成数组

		Lang.each(positions, new Each<Integer>() {

			@Override
			public void invoke(int index, Integer i, int length) throws ExitLoop, ContinueLoop, LoopException {
				temp[index] = i;
			}
		});

		return findByPositions(temp);// 复用调用
	}

	@Override
	public Role findByName(String name) {
		return roleDao.findByCondition(Cnd.where("name", "=", name));
	}

	@Override
	public Role addRole(Role role) {
		return roleDao.save(role);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dgj.boss.service.auth.IRoleService#findById(int)
	 */
	@Override
	public Role findById(int id) {
		return roleDao.findById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dgj.boss.service.auth.IRoleService#upate(com.dgj.model.bean.auth.
	 * Role, java.lang.String[])
	 */
	@Override
	public Result upate(Role role, String... updateField) {
		return roleDao.update(role, updateField) ? Result.success() : Result.fail("更新角色信息失败");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dgj.boss.service.auth.IRoleService#delete(int)
	 */
	@Override
	public Result delete(int id) {
		return roleDao.delById(id) ? Result.success() : Result.fail("删除角色失败");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dgj.boss.service.auth.IRoleService#findAll()
	 */
	@Override
	public List<Role> findAll() {
		return roleDao.findAll();
	}

	@Override
	public Pager<Role> findByPage(int page) {
		Pager<Role> pager = new Pager<Role>(PAGESIZE, page);
		pager.setEntities(roleDao.searchByPage(null, page, PAGESIZE));
		pager.setCount(roleDao.countAll());
		return pager;

	}

	@Override
	public Pager<Role> searchByKey(int page, String key) {
		String searchKey = String.format("%%%s%%", key);
		Condition cnd = Cnd.where("name", "like", searchKey).or("description", "like", searchKey);
		Pager<Role> pager = new Pager<Role>(PAGESIZE, page);
		pager.setEntities(roleDao.searchByPage(cnd, page, PAGESIZE));
		pager.setCount(roleDao.countByCnd(cnd));
		return pager;
	}

	/**
	 * @param id
	 */
	@Override
	public List<Record> findRolePermissionByUserId(int id) {
		Sql sql = Sqls.create(sqls.get("find.role.permission.by.role.id"));
		sql.params().set("id", id);
		return SqlActuator.runReport(sql, roleDao.getDao());
	}

	/**
	 * @param ids
	 * @param roleId
	 */
	@Override
	public Result setPermission(int[] ids, int roleId) {
		/**
		 * 1.查询全部权限列表<br>
		 * 2.遍历权限.如果存在,则更新时间.如果不存在则删除,处理之后从目标数组中移除;<br>
		 * 3.遍历余下的目标数组
		 */
		if (ids == null) {
			ids = new int[] {};
		}
		List<Integer> newIds = Lang.array2list(ids, Integer.class);
		Collections.sort(newIds);
		List<RolePermission> rolePermissions = rolePermissionDao.search(Cnd.where("roleId", "=", roleId));
		for (RolePermission role : rolePermissions) {
			int i = 0;
			if ((i = Collections.binarySearch(newIds, role.getPermissionId())) >= 0) {
				newIds.remove(i);
				role.setPowerTime(now());
				rolePermissionDao.update(role);
			} else {
				rolePermissionDao.delById(role.getId());
			}
		}
		for (int pid : newIds) {
			RolePermission rolep = new RolePermission();
			rolep.setRoleId(roleId);
			rolep.setPermissionId(pid);
			rolePermissionDao.save(rolep);
		}
		return Result.success();
	}

}
